import base64
from typing import Optional
from scipy.io import wavfile
import numpy as np
from config import password_context

# 字符串进行base64编码
def base64_str_encode(content: str) -> str:
    content_string_bytes = content.encode("ascii")
    base64_bytes = base64.b64encode(content_string_bytes)
    return base64_bytes.decode("ascii")


def base64_str_decode(base64_content: str) -> str:
    base64_bytes = base64_content.encode("ascii")
    content_string_bytes = base64.b64decode(base64_bytes)
    return content_string_bytes.decode("ascii")

# 计算声音的时长.
# @see: https://stackoverflow.com/questions/5017367/audio-samples-per-second
def calc_timeLine(audio:bytes, sample_rate:int, channel_count:int=1)->float:
    """
    计算声音的时长
    Args:
        audio (_type_): 音频的字节数据
        channel_count (int, optional): 声道数. Defaults to 1.

    Returns:
        float: 返回声音的时长
    """
    tmp = len(audio) / (channel_count * 2)
    return tmp / sample_rate if tmp >= sample_rate else 0.0

def wav_to_whisper_nparray(wav_file_path:str)->np.ndarray|None:
    """
    将wav文件转换成whisper可翻译的numpy数组
    Args:
        wav_file_path (str): wav文件路径

    Returns:
        np.ndarray|None: 若scipy.io.wavfile.read的结果不满足转换要求返回None
    """
    sample_rate, nparr = wavfile.read(wav_file_path)
    # ('[Np]sample rate:%d. numpy length:%s, sharp:%s, type:%s' % (sample_rate, len(nparr), nparr.shape, nparr.dtype))
    # ('[Np]sample rate:16000. numpy length:26624, sharp:(26624,), type:int16)
    if sample_rate==16000 and nparr.dtype == np.int16: # 'expect wav file sample rate=16000 and np dtype=int16'
        audio_np = nparr.flatten().astype(np.float32) / 32768.0
        
        return audio_np
    
    return None

def get_hashed_password(password: str) -> str:
    return password_context.hash(password)

def _is_true(value: Optional[str]) -> bool:
    if value is None:
        return False
    return value.upper() in {"1", "ON", "YES", "TRUE"}

def verify_password(password: str, hashed_pass: str) -> bool:
    return password_context.verify(password, hashed_pass)

